<template>
  <div class="goods-container">
    <div class="goods-header">
      <h1>周边商品管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleAdd">添加商品</el-button>
      </div>
    </div>

    <!-- 商品筛选 -->
    <div class="filter-container">
      <el-select
        v-model="filterStatus"
        placeholder="商品状态"
        class="filter-item"
        clearable
        @change="handleFilter"
      >
        <el-option label="上架" :value="1" />
        <el-option label="下架" :value="0" />
      </el-select>
      <el-select
        v-model="sortBy"
        placeholder="排序方式"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option label="价格从低到高" value="priceAsc" />
        <el-option label="价格从高到低" value="priceDesc" />
        <el-option label="销量从高到低" value="salesDesc" />
        <el-option label="库存从低到高" value="stockAsc" />
      </el-select>
    </div>

    <!-- 商品列表 -->
    <div v-loading="loading">
      <div v-if="goodsList.length === 0 && !loading" class="empty-data">
        <el-empty description="暂无商品数据" />
      </div>

      <div v-else class="goods-grid">
        <el-card
          v-for="item in goodsList"
          :key="item.id"
          class="goods-card"
          shadow="hover"
        >
          <div class="goods-image">
            <el-image
              :src="getImageUrl(item.isMainUrl)"
              fit="cover"
              :preview-src-list="[getImageUrl(item.isMainUrl)]"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div
              class="goods-status"
              :class="{
                'status-on': item.status === 0,
                'status-off': item.status === 1
              }"
            >
              <span>{{ item.status === 0 ? "已上架" : "已下架" }}</span>
            </div>
          </div>

          <div class="goods-info">
            <h3 class="goods-name">{{ item.name }}</h3>
            <div class="goods-desc">{{ item.description }}</div>

            <div class="goods-price">
              <span class="current-price">¥{{ item.currentPrice }}</span>
              <span
                v-if="item.initialPrice > item.currentPrice"
                class="original-price"
                >¥{{ item.initialPrice }}</span
              >
            </div>

            <div class="goods-meta">
              <span>库存: {{ item.stock }}</span>
              <span>销量: {{ item.salesVolume }}</span>
            </div>

            <div class="goods-actions">
              <el-button type="primary" size="small" @click="handleEdit(item)"
                >编辑</el-button
              >
              <el-button
                :type="item.status === 0 ? 'success' : 'warning'"
                size="small"
                @click="handleToggleStatus(item)"
              >
                {{ item.status === 0 ? "上架" : "下架" }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(item)"
                >删除</el-button
              >
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        v-model:current-page="pageParams.current"
        v-model:page-size="pageParams.size"
        :page-sizes="[6, 12, 24, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select
            v-model="formData.category"
            placeholder="请选择商品分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品图片" prop="isMainUrl">
          <el-upload
            ref="uploadRef"
            class="goods-upload"
            action="/image"
            list-type="picture-card"
            :auto-upload="true"
            :limit="1"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            name="files"
            :headers="{
              'Content-Type': 'multipart/form-data'
            }"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            请上传商品主图（建议尺寸：800x800px，大小不超过2MB）
          </div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="initialPrice">
              <el-input-number
                v-model="formData.initialPrice"
                :min="0"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现价" prop="currentPrice">
              <el-input-number
                v-model="formData.currentPrice"
                :min="0"
                :precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="formData.stock"
                :min="0"
                :precision="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Picture, Plus } from "@element-plus/icons-vue";
import {
  getRimGoods,
  getAllPeripheralProductsClassify,
  uploadImage,
  addPeripheralProduct,
  getPeripheralProductsByPage,
  updatePeripheralProduct,
  deletePeripheralProduct
} from "@/api/rim";

// 列表数据和加载状态
const goodsList = ref([]);
const loading = ref(false);
const total = ref(0);

// 分类列表
const categoryList = ref([]);

// 搜索和筛选
const searchKeyword = ref("");
const filterStatus = ref("");
const sortBy = ref("");

// 分页参数
const pageParams = reactive({
  current: 1,
  size: 12 // 增加默认显示条数
});

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const formRef = ref(null);
const formData = reactive({
  id: "",
  name: "",
  description: "",
  status: 0,
  initialPrice: 0,
  currentPrice: 0,
  stock: 0,
  isMainUrl: "",
  category: "", // 添加分类字段
  imageFiles: [] // 存储图片文件
});

// 上传相关
const fileList = ref([]);
const uploadRef = ref(null);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
  ],
  initialPrice: [
    { required: true, message: "请输入商品原价", trigger: "blur" }
  ],
  currentPrice: [
    { required: true, message: "请输入商品现价", trigger: "blur" }
  ],
  stock: [{ required: true, message: "请输入商品库存", trigger: "blur" }],
  category: [{ required: true, message: "请选择商品分类", trigger: "change" }]
};

// 获取图片URL
const getImageUrl = url => {
  if (!url) return "";
  if (url.startsWith("http")) return url;
  // 根据实际情况修改图片路径前缀
  return `${import.meta.env.VITE_IMAGE_URL || ""}${url}`;
};

// 获取商品列表
const fetchGoodsList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = { ...pageParams };
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }
    if (filterStatus.value !== "") {
      params.status = filterStatus.value;
    }

    // 排序处理
    if (sortBy.value) {
      switch (sortBy.value) {
        case "priceAsc":
          params.orderBy = "currentPrice";
          params.orderType = "asc";
          break;
        case "priceDesc":
          params.orderBy = "currentPrice";
          params.orderType = "desc";
          break;
        case "salesDesc":
          params.orderBy = "salesVolume";
          params.orderType = "desc";
          break;
        case "stockAsc":
          params.orderBy = "stock";
          params.orderType = "asc";
          break;
      }
    }

    const res = await getPeripheralProductsByPage(params);
    // 判断响应数据结构并正确提取数据
    if (res.data && res.data.records) {
      // 如果数据在 data.records 中
      goodsList.value = res.data.records;
      total.value = res.data.total || 0;
    } else if (res.data && res.data.result) {
      // 如果数据在 data.result 中
      goodsList.value = res.data.result;
      total.value = res.data.total || 0;
    } else if (res.records) {
      // 如果数据直接在 records 中
      goodsList.value = res.records;
      total.value = res.total || 0;
    } else {
      // 兜底处理
      goodsList.value = res.data || [];
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pageParams.current = 1;
  fetchGoodsList();
};

// 筛选
const handleFilter = () => {
  pageParams.current = 1;
  fetchGoodsList();
};

// 分页变化
const handleSizeChange = size => {
  pageParams.size = size;
  fetchGoodsList();
};

const handleCurrentChange = current => {
  pageParams.current = current;
  fetchGoodsList();
};

// 添加商品
const handleAdd = () => {
  dialogType.value = "add";
  resetForm();
  // 清空文件列表
  fileList.value = [];
  formData.status = 0; // 默认下架状态
  dialogVisible.value = true;
};

// 编辑商品
const handleEdit = row => {
  dialogType.value = "edit";
  resetForm();

  // 获取图片URL - 处理嵌套数组格式 [["image.webp"]]
  let imageUrl = "";
  if (row.images) {
    if (Array.isArray(row.images)) {
      // 处理嵌套数组 [["image.webp"]]
      if (Array.isArray(row.images[0])) {
        imageUrl = row.images[0][0] || "";
      }
      // 处理普通数组 ["image.webp"]
      else if (row.images.length > 0) {
        imageUrl = row.images[0];
      }
    }
    // 处理字符串情况
    else {
      imageUrl = row.images;
    }
  }

  console.log("处理后的图片URL:", imageUrl);

  // 设置表单数据
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    description: row.description,
    status: row.status,
    initialPrice: row.initialPrice,
    currentPrice: row.currentPrice,
    stock: row.stock,
    category: row.peripheralProductsClassifyId, // 使用分类ID
    isMainUrl: imageUrl // 使用处理后的图片URL
  });

  // 清空之前的图片文件，因为编辑时可能使用已有图片
  formData.imageFiles = [];

  // 如果有图片，添加到预览
  if (formData.isMainUrl) {
    const previewUrl = getImageUrl(formData.isMainUrl);
    fileList.value = [
      {
        name: "商品图片",
        url: previewUrl
      }
    ];
  } else {
    fileList.value = [];
  }

  dialogVisible.value = true;
};

// 切换商品状态
const handleToggleStatus = row => {
  const newStatus = row.status === 0 ? 1 : 0;
  const statusText = newStatus === 1 ? "上架" : "下架";

  ElMessageBox.confirm(`确认要${statusText}商品"${row.name}"吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await updatePeripheralProduct({
          id: row.id,
          status: newStatus
        });
        ElMessage.success(`${statusText}成功`);
        fetchGoodsList();
      } catch (error) {
        console.error(`${statusText}失败:`, error);
        ElMessage.error(`${statusText}失败`);
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 删除商品
const handleDelete = row => {
  ElMessageBox.confirm(`确认要删除商品"${row.name}"吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 直接传递ID，不做转换
        await deletePeripheralProduct([row.id]);
        ElMessage.success("删除成功");
        fetchGoodsList();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 完全重置所有字段
  Object.assign(formData, {
    id: "",
    name: "",
    description: "",
    status: 0,
    initialPrice: 0,
    currentPrice: 0,
    stock: 0,
    isMainUrl: "",
    category: "",
    imageFiles: []
  });

  // 清空文件列表
  fileList.value = [];
};

// 获取所有分类
const fetchAllCategories = async () => {
  try {
    const res = await getAllPeripheralProductsClassify();
    // 处理分类数据，转换为选项格式
    if (res.data && Array.isArray(res.data)) {
      // 如果后端返回的是分类数组
      categoryList.value = res.data.map(item => {
        // 如果是对象，使用id和name
        if (typeof item === "object" && item !== null) {
          return {
            label: item.name || item.label || item.title || "未命名",
            value: item.id
          };
        }
        // 如果是字符串，可能是直接返回的分类名称
        return {
          label: item,
          value: item
        };
      });
    } else if (res.data && res.data.records) {
      // 如果后端返回的是对象数组
      categoryList.value = res.data.records.map(item => ({
        label: item.name,
        value: item.id
      }));
    } else {
      categoryList.value = [];
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
    ElMessage.error("获取分类列表失败");
  }
};

// 图片上传前检查
const beforeUpload = file => {
  // 检查文件类型和大小
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }

  // 将文件添加到表单数据
  formData.imageFiles = [file];

  // 创建本地预览
  fileList.value = [
    {
      name: file.name,
      url: URL.createObjectURL(file)
    }
  ];

  console.log("已选择图片:", file.name);

  return true; // 允许自动上传
};

// 处理上传成功
const handleUploadSuccess = (response, uploadFile) => {
  console.log("图片上传成功:", response);

  // 根据实际接口返回结构获取图片URL
  if (response.code === 200 || response.code === 0) {
    if (response.data) {
      formData.isMainUrl = response.data;
      console.log("设置图片URL(data):", formData.isMainUrl);
    } else if (response.url) {
      formData.isMainUrl = response.url;
      console.log("设置图片URL(url):", formData.isMainUrl);
    } else {
      // 尝试其他可能的返回格式
      const possibleFields = ["url", "path", "imageUrl", "imgUrl", "src"];
      let foundUrl = false;
      for (const field of possibleFields) {
        if (response[field]) {
          formData.isMainUrl = response[field];
          console.log(`设置图片URL(${field}):`, formData.isMainUrl);
          foundUrl = true;
          break;
        }
      }

      // 如果找不到任何URL字段，直接使用整个响应作为URL
      if (!foundUrl && typeof response === "string") {
        formData.isMainUrl = response;
        console.log("使用响应字符串作为URL:", formData.isMainUrl);
      }
    }
  } else {
    ElMessage.error("图片上传失败");
    console.error("图片上传失败，响应:", response);
  }
};

// 移除图片
const handleRemove = () => {
  formData.imageFiles = [];
  formData.isMainUrl = ""; // 同时清除图片URL
  fileList.value = [];
  console.log("已移除图片");
};

// 图片预览
const handlePictureCardPreview = file => {
  if (file.url) {
    const previewUrl = file.url;
    const previewWindow = window.open("", "_blank");
    previewWindow.document.write(
      `<img src="${previewUrl}" style="max-width: 100%; max-height: 100%;" />`
    );
  }
};

// 提交表单
const submitForm = async () => {
  // 表单验证
  if (!formRef.value) return;

  console.log("开始表单验证");
  console.log(
    "当前表单数据:",
    JSON.stringify({
      ...formData,
      imageFiles: formData.imageFiles
        ? formData.imageFiles.length + "个文件"
        : "无文件"
    })
  );

  await formRef.value.validate(async valid => {
    if (!valid) {
      ElMessage.error("请填写完整的商品信息");
      return;
    }

    try {
      console.log("表单验证通过，准备处理图片");

      // 判断是否需要上传图片 - 如果使用了自动上传，这里就不需要再手动上传了
      if (
        formData.imageFiles &&
        formData.imageFiles.length > 0 &&
        !formData.isMainUrl
      ) {
        console.log("准备上传图片...");
        // 创建FormData对象用于上传
        const uploadFormData = new FormData();
        uploadFormData.append("files", formData.imageFiles[0]);

        // 上传图片
        const uploadRes = await uploadImage(uploadFormData);

        // 检查上传结果并获取图片URL
        if (uploadRes.code === 200 || uploadRes.code === 0) {
          // 根据实际接口返回结构获取图片URL
          if (uploadRes.data) {
            formData.isMainUrl = uploadRes.data;
          } else if (uploadRes.url) {
            formData.isMainUrl = uploadRes.url;
          }
        } else {
          ElMessage.error("图片上传失败");
          return;
        }
      } else if (dialogType.value === "add" && !formData.isMainUrl) {
        // 新增商品必须上传图片
        ElMessage.error("请上传商品图片");
        return;
      }

      // 构建提交的商品数据
      const productData = {
        name: formData.name,
        description: formData.description,
        initialPrice: formData.initialPrice,
        currentPrice: formData.currentPrice,
        stock: formData.stock,
        status: formData.status,
        peripheralProductsClassifyId: formData.category,
        images: formData.isMainUrl[0]
      };

      console.log("准备提交商品数据:", productData);

      // 根据操作类型决定调用添加或更新API
      if (dialogType.value === "add") {
        // 添加商品
        const res = await addPeripheralProduct(productData);
        console.log("添加商品结果:", res);
        ElMessage.success("添加商品成功");
      } else {
        // 更新商品
        const res = await updatePeripheralProduct({
          ...productData,
          id: formData.id
        });
        console.log("更新商品结果:", res);
        ElMessage.success("更新商品成功");
      }

      // 关闭弹窗并刷新列表
      dialogVisible.value = false;
      fetchGoodsList();
    } catch (error) {
      console.error("提交商品数据失败:", error);
      ElMessage.error("提交失败，请重试");
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchGoodsList();
  fetchAllCategories();
});
</script>

<style scoped>
.goods-container {
  padding: 20px;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.filter-item {
  width: 180px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.goods-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s;
}

.goods-card:hover {
  transform: translateY(-5px);
}

.goods-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.goods-image .el-image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.goods-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.status-on {
  background-color: #67c23a;
}

.status-off {
  background-color: #909399;
}

.goods-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.goods-desc {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 40px;
}

.goods-price {
  margin-bottom: 10px;
}

.current-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  margin-right: 8px;
}

.original-price {
  font-size: 14px;
  color: #909399;
  text-decoration: line-through;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #606266;
  font-size: 13px;
}

.goods-actions {
  margin-top: auto;
  display: flex;
  gap: 8px;
}

.empty-data {
  padding: 40px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.goods-upload {
  display: flex;
  justify-content: center;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>
